var $ = require('jquery');
var util = require('imutil');
var Mask = require('mask');
var Backbone = require('backbone');
var tpl = require('../tpl');
//var i18n = require('../i18n');

var defaults = {
	el: null,
	tmpl: tpl.loading,
	txt: 'Initializing'
};

var Loading = function(config){
	this.setConfig(config);
	this.__init();
};

Loading.prototype = {
	constructor: Loading,
	
	_: {},
	elems: {},
	
	__init: function(){
		this.elems.$el = $(this.config.el);
	},
	setConfig: function(cfg){
		this.config = util.extend({}, defaults, cfg);
	},
	center: function(){
		var _this = this;

		// 等待ui刷新
		setTimeout(function(){
			//var w = _this.elems.$content.width();
			var h = _this.elems.$content.height();
			var win = util.winSize();
			var pt = parseFloat(_this.elems.$content.css('paddingTop')) || 0;
			var pb = parseFloat(_this.elems.$content.css('paddingBottom')) || 0;
			//var pl = parseFloat(_this.elems.$content.css('paddingLeft')) || 0;
			//var pr = parseFloat(_this.elems.$content.css('paddingRight')) || 0;
			
			// 弹窗上下空白距离比例是 3:6
			var top = (win.height - h - pt - pb) * (3 / 9);
			//var left = (win.width - w - pl - pr) / 2;

			_this.elems.$content.css({
				top: top//,
				//left: left
			});
		}, 0);
	},
	show: function(){
		var _this = this;
		
		this.elems.$content = $(_this.config.tmpl({txt: _this.config.txt || ''}));
		
		this.mask = new Mask({
			el: this.config.el,
			className: {
				show: 'im-anim-fadeIn-fff',
				hide: ''
			},
			clickToHide: false,
			autoShow: true,
			content: this.elems.$content
		});
		
		this.mask.ready(function(){
			//_this.mask.content(_this.elems.$content);
			_this.center();
			_this.trigger('show');
		});
	},
	hide: function(){
		var _this = this;
		
		this.elems.$content && this.elems.$content.addClass('im-anim-loading-hide');
		
		// 延时是根据css动画隐藏loading图标时间定的
		setTimeout(function(){
			_this.mask && _this.mask.dispose();
			_this.trigger('hide');
		}, 499);
		
	},
	dispose: function(){
		this.mask && this.mask.dispose();
	},
	text: function(txt){
		this.config.txt = txt || '';
		this.elems.$content && this.elems.$content.find('.J-im-txt-loading').html(txt);
		this.center();
	}
};

util.extend(Loading.prototype, Backbone.Events);


module.exports = Loading;